﻿using Furion;
using Serilog;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;
using Vben.Admin.Init;
using Vben.Core.Framework.Security;
using Vben.Core.Module.Mon;

namespace Vben.Admin;

public class Startup : AppStartup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // 统一配置项目选项注册
        services.AddProjectOptions();

        services.AddHttpRemote();

        services.AddSqlSugarSetup(Furion.App.Configuration);

        services.AddJwt<AuthzHandler>(enableGlobalAuthorize: true);

        services.AddCorsAccessor();

        services.AddControllers()
            .AddMvcFilter<RequestActionFilter>()
            .AddMvcFilter<MyUnitOfWorkFilter>()
            .AddInjectWithUnifyResult<RestResultProvider>()
            .AddJsonOptions(options =>
            {
                //options.JsonSerializerOptions.DefaultBufferSize = 10_0000;//返回较大数据数据序列化时会截断，原因：默认缓冲区大小（以字节为单位）为16384。
                options.JsonSerializerOptions.Converters.AddDateTimeTypeConverters("yyyy-MM-dd HH:mm:ss");
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // 忽略循环引用 仅.NET 6支持
            });

        // App.GetService<ISysTimerService>().StartTimerJob();
        // 注册日志事件订阅者(支持自定义消息队列组件)
        services.AddEventBus(builder =>
        {
            builder.AddSubscriber<LogEventSubscriber>();
        });

        // services.AddEventBus(builder =>
        // {
        //     builder.AddSubscriber<SiEkpTodoSubscriber>();
        // });
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        YitIdHelper.SetIdGenerator(new IdGeneratorOptions
        {
            WorkerId = 1, // 工作节点ID
            WorkerIdBitLength = 10, // 默认10，支持最多1024个节点
            SeqBitLength = 12, // 默认12，每毫秒可生成4096个ID
            BaseTime = DateTime.Parse("2020-01-01") // 基准时间
        });

        // app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseSerilogRequestLogging(); // 请求日志必须在 UseStaticFiles 和 UseRouting 之间
        app.UseRouting();

        app.UseCorsAccessor();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseInject(string.Empty);

        app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

        Furion.App.GetService<DbSeedService>().Init();
    }
}